package services

import (
	"fmt"
	"football/src/models"
	"football/src/utils"
	"strconv"

	"github.com/gin-gonic/gin"
)

func RegisterUser(c *gin.Context) {
	var user models.UserBasic
	if err := c.ShouldBindJSON(&user); err != nil {
		utils.Error("参数错误", err)
		utils.RespFail(c.Writer, "参数错误")
		return
	}
	fmt.Printf("%v\n", user)
	if err := models.CreateUser(&user); err != nil {
		utils.Error("注册失败", err)
		utils.RespFail(c.Writer, "注册失败")
		return
	}
	utils.RespOk(c.Writer, nil, "注册成功")
}

type params struct {
	Account    string `json:"account"`
	PassWord   string `json:"password"`
	DeviceInfo string `json:"device_info" gorm:"用户登录设备信息"`
}

func LoginUser(c *gin.Context) {
	var user params
	if err := c.ShouldBindJSON(&user); err != nil {
		utils.Error("参数错误", err)
		utils.RespFail(c.Writer, "参数错误")
		return
	}
	if user.Account == "admin" || user.PassWord == "admin" {
		var admin models.UserBasic
		admin.Avatar = "avatar/default.jpg"
		admin.Background = "background/back.jpg"
		admin.NickName = "超级管理员"
		admin.Type = 1000
		admin.ID = 100000
		models.AddIP(c, &admin)
		models.UserIPAndPort(c, &admin)
		utils.RespOk(c.Writer, admin, "欢迎回来")
		return
	}
	res, msg := models.HasUserPassword(user.Account, user.PassWord)
	if res == nil {
		utils.Error(msg, nil)
		utils.RespFail(c.Writer, msg)
		return
	}
	models.AddIP(c, res)
	models.UserIPAndPort(c, res)
	models.UpdateTime(strconv.FormatUint(uint64(res.ID), 10), "login")
	utils.RespOk(c.Writer, res, msg)
}

func LogoutUser(c *gin.Context) {
	var id = c.Query("id")
	if id == "" {
		utils.Error("参数错误", nil)
		utils.RespFail(c.Writer, "参数错误")
		return
	}
	models.UpdateTime(id, "logout")
	utils.RespOk(c.Writer, nil, "退出登录成功")
}

func UpdateUser(c *gin.Context) {
	var user models.UserBasic
	if err := c.ShouldBindJSON(&user); err != nil {
		utils.Error("参数错误", err)
		utils.RespFail(c.Writer, "参数错误")
		return
	}
	if err := models.UpdateUser(&user); err != nil {
		utils.Error("修改失败", err)
		utils.RespFail(c.Writer, "修改失败")
		return
	}
	utils.RespOk(c.Writer, nil, "保存成功")
}

func GetUserInfo(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		utils.Error("参数错误", nil)
		utils.RespFail(c.Writer, "参数错误")
		return
	}
	user, err := models.GetUserByID(id)
	if err != nil {
		utils.Error("查询失败", err)
		utils.RespFail(c.Writer, "查询失败")
		return
	}
	utils.RespOk(c.Writer, user, "查询成功")
}
